from prg.common.object_message import MessageBase
from prg.header_info import HeaderInfo
from prg.server_command import ServerCommand
from prg.entity.arg_entity import ArgBase
from prg.entity.public_entity import PublicEntity
from prg.bll.config_bll import ConfigBll
import socket


class ServerLink(MessageBase):
    def __init__(self):
        super().__init__(name="server_link")
        self.server_socket = None
        self.public_item = PublicEntity.instance()

    def server_start(self):
        link_addr = ConfigBll.instance().get_server().bind
        print("server link listen %s" % link_addr)
        addr_val = link_addr.split("/", 1)
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind((addr_val[0], int(addr_val[1])))
        self.server_socket.listen(10)
        self.start()

    def get_name(self):
        rtn_name = self.public_item.server_id + self.public_item.server_number
        self.public_item.server_number += 1
        return rtn_name

    def entry(self):
        while self.is_run():
            client_socket, client_address = self.server_socket.accept()
            print("server link addr: %s" % str(client_address))
            with client_socket as socket_item:
                header_inf = HeaderInfo(client_socket=socket_item)
                header_en = header_inf.get_head_entity()
                if "bind" == header_en.command:
                    arg = ArgBase()
                    arg.sign = header_en.arg.sign
                    arg.arg_dict = dict()
                    arg.arg_dict["id"] = self.get_name()
                    svr_cmd = ServerCommand()
                    svr_cmd.bind(socket_item=socket_item)
                    svr_cmd.send(command=header_en.command, arg=arg)
                elif "search" == header_en.command:
                    pass
                print("server link command: '%s', addr: %s end" % (header_en.command, client_address))


